// 性能优化工具
export class PerformanceOptimizer {
  constructor() {
    this.imageCache = new Map();
    this.preloadQueue = [];
    this.isPreloading = false;
  }

  // 图片预加载
  preloadImage(src) {
    if (this.imageCache.has(src)) {
      return Promise.resolve(this.imageCache.get(src));
    }

    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => {
        this.imageCache.set(src, img);
        resolve(img);
      };
      img.onerror = reject;
      img.src = src;
    });
  }

  // 批量预加载
  async preloadImages(imageUrls) {
    const promises = imageUrls.map(url => this.preloadImage(url));
    return Promise.allSettled(promises);
  }

  // 关键图片预加载
  preloadCriticalImages() {
    const criticalImages = [
      // 添加您认为重要的图片URL
    ];

    if (criticalImages.length > 0) {
      this.preloadImages(criticalImages);
    }
  }

  // 图片压缩检测
  checkImageOptimization() {
    const images = document.querySelectorAll('img');
    const suggestions = [];

    images.forEach(img => {
      const rect = img.getBoundingClientRect();
      const displaySize = rect.width * rect.height;
      const naturalSize = img.naturalWidth * img.naturalHeight;

      if (naturalSize > displaySize * 4) {
        suggestions.push({
          element: img,
          message: '图片尺寸过大，建议压缩',
          displaySize,
          naturalSize
        });
      }
    });

    return suggestions;
  }

  // 性能监控
  startPerformanceMonitoring() {
    if ('performance' in window) {
      // 监控图片加载性能
      const observer = new PerformanceObserver((list) => {
        list.getEntries().forEach((entry) => {
          if (entry.entryType === 'resource' && entry.name.includes('.jpg') || entry.name.includes('.png')) {
            console.log(`图片加载时间: ${entry.duration}ms`, entry.name);
          }
        });
      });

      observer.observe({ entryTypes: ['resource'] });
    }
  }

  // 内存清理
  cleanup() {
    this.imageCache.clear();
    this.preloadQueue = [];
  }
}

// 全局性能优化实例
export const performanceOptimizer = new PerformanceOptimizer();

// 页面可见性优化
export function optimizeForVisibility() {
  let hidden, visibilityChange;

  if (typeof document.hidden !== "undefined") {
    hidden = "hidden";
    visibilityChange = "visibilitychange";
  } else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
    visibilityChange = "msvisibilitychange";
  } else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
    visibilityChange = "webkitvisibilitychange";
  }

  function handleVisibilityChange() {
    if (document[hidden]) {
      // 页面隐藏时暂停非关键操作
      console.log('页面隐藏，暂停非关键操作');
    } else {
      // 页面显示时恢复操作
      console.log('页面显示，恢复操作');
    }
  }

  if (typeof document.addEventListener !== "undefined" && typeof hidden !== "undefined") {
    document.addEventListener(visibilityChange, handleVisibilityChange, false);
  }
}

// 网络状态优化
export function optimizeForNetwork() {
  if ('connection' in navigator) {
    const connection = navigator.connection;

    if (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g') {
      // 慢速网络优化
      console.log('检测到慢速网络，启用优化模式');
      return 'slow';
    } else if (connection.effectiveType === '3g') {
      // 中等网络优化
      console.log('检测到中等网络，启用标准模式');
      return 'medium';
    } else {
      // 快速网络优化
      console.log('检测到快速网络，启用高性能模式');
      return 'fast';
    }
  }

  return 'unknown';
}
